#!/usr/bin/env python3

# Copyright (c) 2020-2021 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


import os
import abc
from ._util import ActionRunner
from ._errors import CustomActionError


class WindowsInstallationMediaBase:

    def __init__(self):
        self._arch = None
        self._version = None
        self._editions = None
        self._languages = None

    def get_arch(self):
        return self._arch

    def get_version(self):
        return self._version

    def get_editions(self):
        return self._editions

    def get_languages(self):
        return self._languages

    def _set_info(self, os_info):
        self._arch = os_info["arch"]
        self._version = os_info["version"]
        self._editions = os_info["editions"]
        self._languages = os_info["languages"]


class CustomAction(ActionRunner.CustomAction):

    @abc.abstractmethod
    def run(self, action_name, s, ts, work_dir):
        pass

    @classmethod
    def check_object(cls, obj, raise_exception=None):
        assert raise_exception is not None

        if not isinstance(obj, cls):
            if raise_exception:
                raise CustomActionError("invalid object type")
            else:
                return False

        return True

    @staticmethod
    def add_run_command(reg, command):
        key = "HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"
        valueName = "run%d" % (len(reg.get_value_name_list(key)))
        reg.add(key, valueName, "REG_SZ", command)

    @staticmethod
    def add_run_commands(mp, reg, commands):
        # add registry entry
        key = "HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"
        valueName = "run%d" % (len(reg.get_value_name_list(key)))
        reg.add(key, valueName, "REG_SZ", "C:\\%s.bat" % (valueName))

        # add commands into a batch file (put a pause command in the end, so that we can have a end sign)
        buf = ""
        for c in commands:
            buf += c + "\n"
        buf += "pause\n"
        with open(os.path.join(mp, "%s.bat" % (valueName)), "wb") as f:
            f.write(buf.replace("\n", "\r\n").encoding("iso8859-1"))

    @staticmethod
    def add_runonce_command(reg, command):
        key = "HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce"
        valueName = "run%d" % (len(reg.get_value_name_list(key)))
        reg.add(key, valueName, "REG_SZ", command)

    @staticmethod
    def add_runonce_commands(mp, reg, commands):
        # add registry entry
        key = "HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce"
        valueName = "run%d" % (len(reg.get_value_name_list(key)))
        reg.add(key, valueName, "REG_SZ", "C:\\%s.bat" % (valueName))

        # add commands into a batch file (put a pause command in the end, so that we can have a end sign)
        buf = ""
        for c in commands:
            buf += c + "\n"
        buf += "pause\n"
        with open(os.path.join(mp, "%s.bat" % (valueName)), "wb") as f:
            f.write(buf.replace("\n", "\r\n").encoding("iso8859-1"))

    class UserOpSkipPause:
        pass
